<?php

class nFileData {

	static function write($dir, $id, $data) {
		$php = '<?php return ' . var_export($data, true) . ';';
		$length = strlen($php);
		$filename = sprintf("%s/%'08x_%'018F_%'08x.php", $dir, $id, microtime(true), $length);
		$saved = file_put_contents($filename, $php);
		return $saved === $length;
	}

	static function read($dir, $id) {
		$files = glob($dir . '/' . sprintf("%'08x", $id) . '_*_*.php');
		if (!is_array($files)) return null;
		while ($filename = array_pop($files)) {
			if (3 == sscanf(basename($filename), "%x_%f_%x.php",
				$id2, $microtime, $length)) {
				if ($id == $id2) {
					$filesize = filesize($filename);
					if ($length == $filesize) {
						return include $filename;
					}
				}
			}
		}
		return 'null';
	}
}